package com.we823.cms.controller.common;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.we823.cms.common.WebConstants;
import com.we823.cms.common.utils.RequestUtil;

@Controller
@RequestMapping(WebConstants.WEB_PREFIX)
public class CommonController {

	private String baseUrl = "error/";
	@RequestMapping("error")
	public String error(HttpServletRequest request,Model model){
		String ecode = RequestUtil.getValueByName(request,"ecode","error");
        String errorMsg = "";
        Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");

        if(statusCode==404){
            errorMsg = "访问的地址没有找到";
        }
        if(statusCode==null){
            statusCode = 0;
        }
        String uri = (String) request.getAttribute("javax.servlet.error.request_uri");
        String queryString = request.getQueryString();
        String url = uri + (queryString == null || queryString.length() == 0 ? "" : "?" + queryString);

        Throwable exception = (Throwable) request.getAttribute("javax.servlet.error.exception");
        if(exception!=null){

           StackTraceElement[] elements =  exception.getStackTrace();
            StringBuilder sb = new StringBuilder();
            if(elements!=null){
                for(StackTraceElement element : elements){
                    sb.append(element+"<br/>");
                }
                errorMsg = sb.toString();
            }
        }
        model.addAttribute("statusCode",statusCode);
        model.addAttribute("url",url);
        model.addAttribute("errorMsg",errorMsg);
        model.addAttribute("ecode",ecode);
		return baseUrl + "error";
	}
}
